import Icon from '@/components/Icon';
import styles from './index.module.scss';
import dayjs from 'dayjs';
import { CommentType } from '@/store/reducer/comment';
import { useDispatch } from 'react-redux';
import {
  getCommentByIdAction,
  getReplyCommentByIdAction,
  likeCommentAction,
  saveOriginCommentAction,
} from '@/store/action/comment';
import { useAppSelector } from '@/store';
import { Toast } from 'antd-mobile';

type Props = {
  comment: CommentType;
  type?: 'reply' | 'normal' | 'origin';
};

export default function CommentItem({ comment, type = 'normal' }: Props) {
  const dispatch = useDispatch();
  const { detail } = useAppSelector((state) => state.article);
  const { replyData, originComment } = useAppSelector((state) => state.comment);
  const handleClickLike = async () => {
    await dispatch(likeCommentAction(comment.com_id, comment.is_liking));

    if (type === 'origin') {
      const like_count = originComment.is_liking
        ? originComment.like_count - 1
        : originComment.like_count + 1;
      dispatch({
        type: 'comment/saveOriginComment',
        payload: { ...originComment, is_liking: !originComment.is_liking, like_count },
      });
      dispatch(getCommentByIdAction({ type: 'a', source: detail.art_id }));
      Toast.show({ content: comment.is_liking ? '取消点赞' : '点赞成功' });
      return;
    }

    if (!!replyData.results?.length) {
      dispatch(getReplyCommentByIdAction(originComment.com_id));
      Toast.show({ content: comment.is_liking ? '取消点赞' : '点赞成功' });
      return;
    }
    dispatch(getCommentByIdAction({ type: 'a', source: detail.art_id }));
    Toast.show({ content: comment.is_liking ? '取消点赞' : '点赞成功' });
  };
  return (
    <div className={styles.root}>
      <div className="avatar">
        <img src={comment.aut_photo} alt="" />
      </div>

      <div className="comment-info">
        <div className="comment-info-header">
          <span className="name">{comment.aut_name}</span>

          <span className="thumbs-up" onClick={handleClickLike}>
            {comment.like_count}
            <Icon type={comment.is_liking ? 'iconbtn_like_sel' : 'iconbtn_like2'} />
          </span>
        </div>

        <div className="comment-content">{comment.content}</div>

        <div className="comment-footer">
          {type === 'normal' && (
            <span className="replay" onClick={() => dispatch(saveOriginCommentAction(comment))}>
              {comment.reply_count}回复 <Icon type="iconbtn_right" />
            </span>
          )}

          <span className="comment-time">{dayjs(comment.pubdate).toNow()}</span>
        </div>
      </div>
    </div>
  );
}
